using System.Text.Json;

namespace Tool
{
    public class ObjectClone
    {
        //public static T Clone<T>(T realObject)
        //{
        //    using (Stream stream = new MemoryStream())
        //    {
        //        var serializer = new XmlSerializer(typeof(T));
        //        serializer.Serialize(stream, realObject);
        //        stream.Seek(0, SeekOrigin.Begin);
        //        return (T)serializer.Deserialize(stream);
        //    }
        //}
        //public static List<T> Clone<T>(List<T> realObject)
        //{
        //    using (Stream stream = new MemoryStream())
        //    {
        //        var serializer = new XmlSerializer(typeof(T));
        //        serializer.Serialize(stream, realObject);
        //        stream.Seek(0, SeekOrigin.Begin);
        //        return (List<T>)serializer.Deserialize(stream);
        //    }
        //}

        /// <summary>
        /// 不同对象之间的深拷贝，最好属性名一样
        /// </summary>
        /// <typeparam name="T">源对象类型</typeparam>
        /// <typeparam name="F">目的对象类型</typeparam>
        /// <param name="original">源对象</param>
        /// <returns>目的对象</returns>
        public static F DeepCopy<T, F>(T original)
        {
            var json = JsonSerializer.Serialize(original);
            var result = JsonSerializer.Deserialize<F>(json);
            return result;
        }
    }
}